package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.CartListConstant;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.result.Result;
import com.dongdongshop.result.ResultEnum;
import com.dongdongshop.service.CartService;
import com.dongdongshop.util.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {

    private static final Logger logger = LoggerFactory.getLogger(CartController.class);

    @Reference
    private CartService cartService;

    //要往购物车添加数据，就要先拿到购物车里原有的数据
    //购物车的查询
    @RequestMapping("cartList")
    @ResponseBody
    public Result<List<Cart>> cartList(HttpServletRequest request,HttpServletResponse response){
        //获取用户登录信息
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //从cookie查询购物车
        String cookieValue = CookieUtils.getCookieValue(request, CartListConstant.CART_NAME,"utf-8");
        //判断购物车是否位空，避免解析json的时候包空指针
        if (StringUtils.isBlank(cookieValue)){
            cookieValue = "[]";
        }
        List<Cart> carts = JSONObject.parseArray(cookieValue, Cart.class);
        if (null == user){
            return Result.jsonResponse(ResultEnum.OK).setData(carts);
        }else {
            List<Cart> cartFormRedis = cartService.findCartFormRedis(user.getUsername());
            //只有cookie中还有购物车数据才进行合并
            if (carts.size() > 0){
                //合并购物车
                List<Cart> mergeCartList = cartService.mergeCartList(carts, cartFormRedis);
                //合并之后存放到redis中
                cartService.insertCartListToRedis(user.getUsername(),mergeCartList);
                //删除浏览器购物车信息
                CookieUtils.deleteCookie(request,response,CartListConstant.CART_NAME);
                return Result.jsonResponse(ResultEnum.OK).setData(mergeCartList);
            }
            //没有的话就直接放回redis中的购物车数据
            logger.info("执行成功");
            return Result.jsonResponse(ResultEnum.OK).setData(cartFormRedis);
        }
    }
    //向购物车添加商品
    @RequestMapping("insertCartList")
    public String insertCartList(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num, Model model){
        //先查看购物车
        Result<List<Cart>> result = cartList(request,response);
        List<Cart> carts = result.getData();
        //调用购物车服务，添加购物车
        carts = cartService.insertCartList(carts,itemId,num);
        //获取用户登录信息
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (null == user){
            //cookie保存字符串
            CookieUtils.setCookie(request,response,CartListConstant.CART_NAME,JSONObject.toJSONString(carts),24 * 60 * 60,"utf-8");
        }else {
            cartService.insertCartListToRedis(user.getUsername(),carts);
            model.addAttribute("tbUser",user.getUsername());
        }
        logger.info("执行成功");
        return "success-cart";
    }

    @RequestMapping("toCartShow")
    public String toCartShow(Model model){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (null != user){
            model.addAttribute("tbUser",user.getUsername());
        }
        return "cart";
    }

    @RequestMapping("updateCartNumAndPrice")
    @ResponseBody
    private Result updateCartNumAndPrice(HttpServletRequest request, HttpServletResponse response,Long itemId,Integer num,Model model){
        insertCartList(request,response,itemId,num,model);
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("tbUser",user.getUsername());
        logger.info("执行成功");
        return Result.jsonResponse(ResultEnum.OK);
    }
}
